﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using PSE.Framework.ErrorLogging;
using System.Diagnostics;
using PSE.Framework.UI.Resources;
using PSE.Framework.UI.Controls.SmartClient;
using System.IO;
using System.Reflection;
using PSE.Framework.Configuration;
using PSE.Framework.Versions.Engine;
using PSE.Framework.Versions.Common.Entities;
using Microsoft.Win32;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Windows.Threading;

namespace PSE.Framework.Versions.ApplicationBase
{
    /// <summary>
    /// Interaction logic for VersionsWindow.xaml
    /// </summary>
    public partial class VersionsWindow : System.Windows.Window
    {
        private const string CONST_TITLE = "BM&FBOVESPA - {0} v{1}";
        
        public string SystemName { get; set; }
        public int MajorVersion { get; set; }
        
        public Product Product { get; private set; }

        private ObservableCollection<Version> _versions = new ObservableCollection<Version>();

        public ObservableCollection<Version> Versions { get { return _versions; } }

        public VersionsWindow()
        {
            InitializeComponent();
            ChangeIcon();

            this.DataContext = this;
        }

        private void btnAtualizar_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            LoadVersions();
        }

        private void btnCancelar_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            this.Close();
        }

        private void ChangeIcon()
        {
            MemoryStream memoryStream = new MemoryStream();
            PngBitmapDecoder pngBitmapDecoder;
            System.Drawing.Icon icon;
            Stream stream = null;

            Assembly entryAssembly = System.Reflection.Assembly.GetEntryAssembly();

            foreach (string resource in entryAssembly.GetManifestResourceNames())
            {
                if (resource.EndsWith(".ico"))
                {
                    stream = entryAssembly.GetManifestResourceStream(resource);
                    break;
                }
            }

            if (stream != null)
            {
                icon = new System.Drawing.Icon(stream);
                icon.ToBitmap().Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);

                memoryStream.Seek(0, SeekOrigin.Begin);

                pngBitmapDecoder = new PngBitmapDecoder(memoryStream, BitmapCreateOptions.None, BitmapCacheOption.Default);

                this.Icon = pngBitmapDecoder.Frames[0];
            }
        }

        private void InitializeListView()
        {
            this._versions.Clear();

            foreach (var module in this.Product.Modules)
            {
                this._versions.Add(new Version
                {
                    ModuleName = module.ModuleName,
                    Client = module.Versions.Client,
                    Server = module.Versions.Server,
                    ServerUrl = module.Versions.ServerUrl
                });
            }
        }

        private void CreateReport()
        {
            string path = ShowSaveFileDialog();
            if (string.IsNullOrEmpty(path))
                return;

            try
            {
                VersionsDiscovery.Instance.CreateReport(this.Product, path);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, MessageBoxButton.Ok, MessageBoxImage.Error);
            }
        }

        private string ShowSaveFileDialog()
        {
            SaveFileDialog saveFile = new SaveFileDialog();
            saveFile.Filter = "(*.html) |*.html";
            saveFile.FileName = this.Product.Name;
            var result = saveFile.ShowDialog();

            if (!result.HasValue || !result.Value)
                return string.Empty;

            return saveFile.FileName;
        }

        private void btnRelatorio_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            CreateReport();
        }

        private void Window_ContentRendered(object sender, EventArgs e)
        {
            LoadVersions();
        }

        private void LoadVersions()
        {
            this.Title = string.Format(CONST_TITLE, this.SystemName, this.MajorVersion);

            lblLoading.Visibility = System.Windows.Visibility.Visible;
            this.Product = VersionsDiscovery.Instance.Get(this.SystemName, this.MajorVersion);
            InitializeListView();
            lblLoading.Visibility = System.Windows.Visibility.Hidden;
            btnRelatorio.IsEnabled = (this.Product != null);
        }
    }

    public class Version : INotifyPropertyChanged
    {
        private string _moduleName;
        public string ModuleName
        {
            get { return this._moduleName; }
            set
            {
                if (value != this._moduleName)
                {
                    this._moduleName = value;
                    NotifyPropertyChanged("ModuleName");
                }
            }
        }

        private string _client;
        public string Client
        {
            get { return this._client; }
            set
            {
                if (value != this._client)
                {
                    this._client = value;
                    NotifyPropertyChanged("Client");
                }
            }
        }

        private string _server;
        public string Server
        {
            get { return this._server; }
            set
            {
                if (value != this._server)
                {
                    this._server = value;
                    NotifyPropertyChanged("Client");
                }
            }
        }

        private string _serverUrl;
        public string ServerUrl
        {
            get { return this._serverUrl; }
            set
            {
                if (value != this._serverUrl)
                {
                    this._serverUrl = value;
                    NotifyPropertyChanged("ServerUrl");
                }
            }
        }


        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}